package com.day07.homework;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ExerciseList {
    static class Student {
        private String id;
        private String name;
        private Integer age;

        public Student() {
        }

        public Student(String id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    public static void main(String[] args) {
        final String fileName = "test.txt";
        List<Student> list = ExerciseList.sort2List(ExerciseList.arrayList2List(ExerciseList.file2ArrayList(fileName)));
        for (Student stu : list) {
            System.out.println(stu.toString());
        }
    }

    public static ArrayList<String> file2ArrayList(String fileName) {
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader br = new BufferedReader(fr);
            String str;
            while ((str = br.readLine()) != null) {
                arrayList.add(str);
            }
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    public static List<Student> arrayList2List(ArrayList<String> arrayList) {
        String[] tmp;
        List<Student> studentList = new ArrayList<>();
        for (String str : arrayList) {
            tmp = str.split(";");
            studentList.add(new Student(tmp[0], tmp[1], Integer.parseInt(tmp[2])));
        }
        return studentList;
    }

    public static List<Student> sort2List(List<Student> list) {
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge().compareTo(o1.getAge());
            }
        });
        return list;
    }
}

